package com.dyz.leetcode._15_BFSAndDFS;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class _589_preorder {
    // 迭代
    public List<Integer> preorder1(Node root) {
        ArrayList<Integer> res = new ArrayList<>();
        if (root ==null) {return res;}

        Stack<Node> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            Node curr = stack.pop();
            res.add(curr.val);
            // 将 N 个子节点放入到栈中
            List<Node> children = curr.children;
            for (int i = children.size() - 1; i >= 0; i--) {
                stack.push(children.get(i));
            }
        }
        return res;
    }

    // 递归
    public List<Integer> preorder(Node root) {
        ArrayList<Integer> res = new ArrayList<>();
        if (root ==null) {return res;}
        dfs(root, res);
        return res;
    }

    private void dfs(Node node, List<Integer> res) {
        if (node == null) {return;}
        // 处理当前遍历的节点
        res.add(node.val);
        for (Node child : node.children) {
            dfs(child, res);
        }
    }
}
